package sing.core.ext.view

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.PorterDuff
import android.hardware.Camera
import android.os.Build
import android.preference.PreferenceManager
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import sing.core.callback.load_sir.EmptyCallback
import sing.core.callback.load_sir.LoadingCallback
import sing.core.R
import sing.core.base.appContext
import sing.core.callback.load_sir.ErrorCallback

/**
 * 描述　:项目中自定义类的拓展函数
 */

fun LoadService<*>.setErrorText(message: String) {
    if (message.isNotEmpty()) {
        this.setCallBack(ErrorCallback::class.java) { _, view ->
            view.findViewById<TextView>(R.id.error_text).text = message
        }
    }
}


fun LoadService<*>.setEmptyText(message: String) {
    if (message.isNotEmpty()) {
        this.setCallBack(EmptyCallback::class.java) { _, view ->
            view.findViewById<TextView>(R.id.tv_msg).text = message
        }
    }
}

/**
 * 设置错误布局
 * @param message 错误布局显示的提示内容
 */
fun LoadService<*>.showError(message: String = "") {
    this.setErrorText(message)
    this.showCallback(ErrorCallback::class.java)
}

/**
 * 设置空布局
 */
fun LoadService<*>.showEmpty(message: String = "") {
    this.setEmptyText(message)
    this.showCallback(EmptyCallback::class.java)
}

/**
 * 设置加载中
 */
fun LoadService<*>.showLoading() {
    this.showCallback(LoadingCallback::class.java)
}

fun loadServiceInit(view: View, callback: () -> Unit): LoadService<Any> {
    val loadsir = LoadSir.getDefault().register(view) {
        callback.invoke()//点击重试时触发的操作
    }
    loadsir.showSuccess()
    loadsir.setCallBack(LoadingCallback::class.java) { _, view ->
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            view.findViewById<ProgressBar>(R.id.loading_progress).indeterminateTintMode = PorterDuff.Mode.SRC_ATOP
            view.findViewById<ProgressBar>(R.id.loading_progress).indeterminateTintList = getOneColorStateList(getColor(appContext))
        }
    }
    return loadsir
}

fun getOneColorStateList(color: Int): ColorStateList {
    val colors = intArrayOf(color)
    val states = arrayOfNulls<IntArray>(1)
    states[0] = intArrayOf()
    return ColorStateList(states, colors)
}
/**
 * 获取当前主题颜色
 */
fun getColor(context: Context): Int {
    val setting = PreferenceManager.getDefaultSharedPreferences(context)
    val defaultColor = ContextCompat.getColor(context, R.color.main_color)
    val color = setting.getInt("color", defaultColor)
    return if (color != 0 && Color.alpha(color) != 255) {
        defaultColor
    } else {
        color
    }
}
